/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package edu.fsu.cs.cis5930;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the main Activity that displays the current chat session.
 */
public class BusinessCardExpress extends Activity {
    // Debugging
    private static final String TAG = "BluetoothChat";
    private static final boolean D = true;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    // Layout Views
    private TextView mTitle;
    // private ListView mConversationView;
    /*
    private EditText mOutEditText;
    private Button mSendButton;
*/
    // Name of the connected device
    private String mConnectedDeviceName = null;
    // Array adapter for the conversation thread
    // private ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothCardService mCardService = null;
    private CardAdapter mCardAdapter;
    private ContentProviderBackup mContentProvider;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(D) Log.e(TAG, "+++ ON CREATE +++");

        // Set up the window layout
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

        // Set up the custom title
        mTitle = (TextView) findViewById(R.id.title_left_text);
        mTitle.setText(R.string.app_name);
        mTitle = (TextView) findViewById(R.id.title_right_text);

        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mContentProvider = new ContentProviderBackup(this);
        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");
        
        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        
            // Otherwise, setup the chat session
        } else {
            if (mCardService == null) mCardService = new BluetoothCardService(this, mHandler);;
        }
        
        

        
        List<BusinessCard> myList = new LinkedList<BusinessCard>();
      
        myList = mContentProvider.getAllCards();

        mCardAdapter = new CardAdapter(this, myList);
        ListView mCardView = (ListView) findViewById(R.id.cardView);
        mCardView.setAdapter( mCardAdapter );
        final Context myContext = this;
        mCardView.setOnItemClickListener( new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				final BusinessCard clickedCard = mCardAdapter.getItem(arg2);
				new AlertDialog.Builder(myContext)
			  //  .setTitle(clickedCard.getName())
			    .setMessage(clickedCard.getName() + "\n" + clickedCard.email + "\n" + clickedCard.phone_number)
			    .setPositiveButton("Call", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							   Intent intent = new Intent(Intent.ACTION_CALL);
							   intent.setData(Uri.parse("tel:" + clickedCard.phone_number));
							   startActivity(intent);
						
						
					}
			     })
			     .setNeutralButton("Email", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
							emailIntent .setType("plain/text");
							emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{clickedCard.email});
							startActivity(Intent.createChooser(emailIntent, "Send mail..."));
						
					}
			     })
			    .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
				
						mContentProvider.deleteCard( clickedCard.ID);
						mCardAdapter.removeItem(clickedCard);
						
					}
			     })
			     .show();
				 
			}
		});
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mCardService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mCardService.getState() == BluetoothCardService.STATE_NONE) {
              // Start the Bluetooth chat services
              mCardService.start();
            }
        }
    }
    /*
    private void setupChat() {
        Log.d(TAG, "setupChat()");

        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        mConversationView = (ListView) findViewById(R.id.in);
        mConversationView.setAdapter(mConversationArrayAdapter);
        
       
        // Initialize the compose field with a listener for the return key
        mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        mOutEditText.setOnEditorActionListener(mWriteListener);

        // Initialize the send button with a listener that for click events
        mSendButton = (Button) findViewById(R.id.button_send);
        mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Send a message using content of the edit text widget
                TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message = view.getText().toString();
                sendMessage(message);
            }
        });

        // Initialize the BluetoothChatService to perform bluetooth connections
        mCardService = new BluetoothCardService(this, mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }*/

    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mCardService != null) mCardService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }

    private void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    private byte[] convertBusinessCardToByteArray(BusinessCard b) {	
    	ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    	ObjectOutputStream oos = null;
    	byte[] buf = null;
		try {
			oos = new ObjectOutputStream(baos);
		} catch (IOException e) {
			Log.e(TAG, "Error creating ObjectOutputStream", e);
		}
		if(oos != null) {
			try {
				oos.writeObject(b);
			} catch (IOException e) {
				Log.e(TAG, "Error in oos.writeObject", e);
			}
			buf = baos.toByteArray();
		}    	
       	
       	return buf;
    }
    
    private BusinessCard convertByteArrayToBusinessCard(byte[] buf) {
    	ObjectInputStream ois = null;
    	BusinessCard b = null;
    	
    	try {
    		ois = new ObjectInputStream(new ByteArrayInputStream(buf));
    	} catch (Exception e) {
    		Log.e(TAG, "Could not create ObjectInputStream", e);
    	}
    	
    	if(ois != null) {
 	   		try {
 	   			b = (BusinessCard) ois.readObject();
 	   			ois.close();
 	   		} catch (Exception e) {
 	   			Log.e(TAG, "Error reading ObjectInputStream", e);
 	   		}
    	}
    	
    	return b;
    }
    
    /**
     * Sends a message.
     * @param message  A string of text to send.
     */
    private void sendCard(BusinessCard b) {
        // Check that we're actually connected before trying anything
        if (mCardService.getState() != BluetoothCardService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        byte[] send = convertBusinessCardToByteArray(b);
        mCardService.write(send);
        /*
        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mCardService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            
            mOutEditText.setText(mOutStringBuffer);
        }*/
    }

    /*
    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                sendMessage(message);
            }
            if(D) Log.i(TAG, "END onEditorAction");
            return true;
        }
    };
    */

    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothCardService.STATE_CONNECTED:
                    mTitle.setText(R.string.title_connected_to);
                    mTitle.append(mConnectedDeviceName);
                  
                    BusinessCard test = mContentProvider.getMyCard();
                    sendCard(test);
                    break;
                case BluetoothCardService.STATE_CONNECTING:
                    mTitle.setText(R.string.title_connecting);
                    break;
                case BluetoothCardService.STATE_LISTEN:
                case BluetoothCardService.STATE_NONE:
                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_WRITE:
            	Toast.makeText(getApplicationContext(), "Sent card.", Toast.LENGTH_SHORT).show();
                //byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                //String writeMessage = new String(writeBuf);
                //mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                BusinessCard b = convertByteArrayToBusinessCard(readBuf);
                Toast.makeText(getApplicationContext(), "Received card from" + b.first_name, Toast.LENGTH_LONG).show();
                mContentProvider.insertCard(b);
                mCardAdapter.addItem(b);
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                mCardService.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
            	mCardService = new BluetoothCardService(this, mHandler);
            } else {
                // User did not enable Bluetooth or an error occured
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.send_card:
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        case R.id.receive_card:
            // Ensure this device is discoverable by others
            ensureDiscoverable();
            return true;
        case R.id.edit_card:
        	// Launch the EditCardActivity to change the stored card on device
        	Intent screenIntent = new Intent(this, EditCardActivity.class);
        	startActivity(screenIntent);
        }
        return false;
    }
    
    // Display current business card fields, and allow the user to change them
    public static class EditCardActivity extends Activity
    {
    	EditText firstName;
    	EditText lastName;
    	EditText phone;
    	EditText email;
    	private ContentProviderBackup mContentProvider;
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.card_edit);
            
            ImageButton saveButton = (ImageButton) findViewById(R.id.edit_button_save);
            ImageButton cancelButton = (ImageButton) findViewById(R.id.edit_button_cancel);
            mContentProvider = new ContentProviderBackup(this);
            
            cancelButton.setOnClickListener( new OnClickListener() {
					public void onClick(View v) {
					finish();
					
				}
			});
            
            saveButton.setOnClickListener( new OnClickListener() {
				public void onClick(View v) {
				BusinessCard myCard = new BusinessCard();
				myCard.first_name = firstName.getText().toString();
				myCard.last_name = lastName.getText().toString();
				myCard.phone_number = phone.getText().toString();
				myCard.email = email.getText().toString();
				
				
				mContentProvider.setMyCard(myCard);
				
				finish();
				
			}
		});
        }
    	
        public void onStart() {
            super.onStart();
          
            BusinessCard myCard;
            
            myCard = new BusinessCard();
           
            myCard = mContentProvider.getMyCard();
            
             firstName = (EditText) findViewById(R.id.field_name_first);
            lastName = (EditText) findViewById(R.id.field_name_last);
            phone = (EditText) findViewById(R.id.field_phone);
            email = (EditText) findViewById(R.id.field_email);
            
            firstName.setText( myCard.first_name);
            lastName.setText( myCard.last_name);
            phone.setText( myCard.phone_number);
            email.setText( myCard.email);
        }
    
    }

    public static class CardAdapter extends BaseAdapter
    {
    	private Context mContext;
    	private List<BusinessCard> mList;
    	
    	

		public CardAdapter(Context context,
				List<BusinessCard> myList) {
			this.mContext = context;
			this.mList = myList;
		}

		public int getCount() {
			return mList.size();
		}

		public BusinessCard getItem(int position) {
			return mList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}
		
		public void addItem(BusinessCard c)
		{
			mList.add(c);
		}
		
		public void removeItem(BusinessCard c)
		{
			mList.remove(c);
			notifyDataSetChanged();
		}

		public View getView(int position, View convertView, ViewGroup viewGroup) {
	        BusinessCard entry = mList.get(position);
	        if (convertView == null) {
	            LayoutInflater inflater = (LayoutInflater) mContext
	                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            convertView = inflater.inflate(R.layout.card_layout, null);
	        }
	        TextView first_name = (TextView) convertView.findViewById(R.id.card_first_name);
	        first_name.setText(entry.first_name);

	        TextView second_name = (TextView) convertView.findViewById(R.id.card_last_name);
	        second_name.setText(entry.last_name);

	        TextView phone = (TextView) convertView.findViewById(R.id.card_phone);
	        phone.setText(entry.phone_number);
	        
	        TextView email = (TextView) convertView.findViewById(R.id.card_email);
	        email.setText(entry.email);


	        return convertView;
	    
		}
    	
    
    }
}